package com.quanyan.ic.vendingMachine.dao.impl;

import com.alibaba.fastjson.JSON;
import com.quanyan.ic.vendingMachine.dao.VmCategoryDAO;
import com.quanyan.ic.vendingMachine.mapper.VmCategoryEntityMapper;
import com.quanyan.ic.vendingMachine.mapper.entity.VmCategoryEntity;
import com.quanyan.ic.vendingMachine.mapper.entity.VmCategoryEntityExample;
import com.quanyan.ic.vendingMachine.model.Image;
import com.quanyan.ic.vendingMachine.model.VmCategory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhuo.shi on 2017/7/25.
 */
@Repository
public class VmCategoryDAOImpl implements VmCategoryDAO {

    @Autowired
    VmCategoryEntityMapper vmCategoryEntityMapper;

    //    @Cacheable(value = "vm_category")
    @Override
    public List<VmCategory> listAll() {
        List<VmCategoryEntity> vmCategoryEntities = vmCategoryEntityMapper.selectByExample(new VmCategoryEntityExample());
        List<VmCategory> resultList = new ArrayList<>();
        for (VmCategoryEntity entity : vmCategoryEntities) {
            resultList.add(toModel(entity));
        }
        return resultList;
    }

    //    @Cacheable(value = "vm_category", key = "#id")
    @Override
    public VmCategory findById(Integer id) {
        VmCategoryEntity vmCategoryEntity = vmCategoryEntityMapper.selectByPrimaryKey(id);
        return toModel(vmCategoryEntity);
    }

    //    @CacheEvict(value = "vm_category", key = "#id")
    @Override
    public void deleteById(Integer id) {
        vmCategoryEntityMapper.deleteByPrimaryKey(id);
    }

    private VmCategory toModel(VmCategoryEntity entity) {
        VmCategory vmCategory = new VmCategory();
        vmCategory.setId(entity.getId());
        vmCategory.setName(entity.getName());
        try {
            vmCategory.setGridXY(JSON.parseArray(entity.getGridXY(), Integer.class));
            vmCategory.setGridZ(JSON.parseArray(entity.getGridZ(), Integer.class));
        } catch (Exception e) {
            e.printStackTrace();
        }
        vmCategory.setGridStartNumber(entity.getGridStartNumber());
        Image image = new Image();
        image.setImgUrl_S(entity.getSmallImgUrl());
        image.setImgUrl_M(entity.getMiddleImgUrl());
        image.setImgUrl_L(entity.getLargeImgUrl());
        vmCategory.setImg(image);
        vmCategory.setEnable(entity.getIsEnable());
        return vmCategory;
    }
}
